package com.aikg.kgrag_java.pojo.vo;

import io.minio.messages.Item;
import lombok.Builder;
import lombok.Data;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Objects;
import com.google.common.collect.Lists;
import io.minio.Result;
import lombok.NoArgsConstructor;

@Data
@Builder
public class ObjectVO{
    private String etag; // except DeleteMarker

    private String objectName;

    private ZonedDateTime lastModified;

    // private Owner owner;

    private long size; // except DeleteMarker

    private String storageClass; // except DeleteMarker, not in case of MinIO server.

    private boolean isLatest; // except ListObjects V1

    private String versionId; // except ListObjects V1

    // private Metadata userMetadata;

    @Builder.Default
    private boolean isDir = false;

    // private String encodingType = null;

    /**
     * 将 MinIO 的 Item 转换为 ObjectVO
     */
    public static ObjectVO fromItem(Item item) {
        if (Objects.isNull(item)) {
            return null;
        }
        // 在这里检查 lastModified 是否为 null，避免空指针异常
        ZonedDateTime lastModifiedDate = null;
        if (item.lastModified() != null) {
            lastModifiedDate = ZonedDateTime.ofInstant(item.lastModified().toInstant(), ZoneId.systemDefault());
        }
        return ObjectVO.builder()
                .etag(item.etag())
                .objectName(item.objectName())
                .lastModified(lastModifiedDate)  // 处理 null 的情况
                .size(item.size())
                .storageClass(item.storageClass())
                .isLatest(item.isLatest())
                .versionId(item.versionId())
                .isDir(item.isDir())
                .build();
    }

    /**
     * 将 Iterable<Result<Item>> 转换为 List<ObjectVO>
     */
    public static List<ObjectVO> fromResItem(Iterable<Result<Item>> items) {
        List<ObjectVO> list = Lists.newArrayList();
        if (Objects.isNull(items)) {
            return list;
        }

        items.forEach(resItem -> {
            try {
                list.add(fromItem(resItem.get()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return list;
    }
}
